package com.atguigu.gmall.common.util;

import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.util.ClassUtils;

/**
 * @author wk
 * @create 2021-08-26 11:12
 */
public class FastDFSUtils {
    static {
        String path = ClassUtils.getDefaultClassLoader().getResource("fdfs_client.conf").getPath();
        try {
            ClientGlobal.init(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String upload(byte[] file, String originalFilename) {
        // 1.设置跟踪器的IP和端口号
        // String path1 = FastDFS.class.getClass().getClassLoader().getResource("fdfs_client.conf").getPath();
        // 使用工具类获取到文件的路径
        try {
            // 2.客户端连接跟踪器
            TrackerClient client = new TrackerClient();
            // 3.获取存储结点的IP和端口号
            TrackerServer trackerServer = client.getConnection();
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, null);
            // 获取文件后缀名
            String extension = FilenameUtils.getExtension(originalFilename);
            // 4.存储文件
            String fileId = storageClient1.upload_file1(file, extension, null);
            return fileId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
